package com.frank.subject.infra.basic.utils;

import com.alibaba.druid.filter.config.ConfigTools;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * @author Climb Zou
 * @version v0.0.1
 * @date 2024/1/19 16:41
 * @description 数据库信息加密
 */
public class DruidEncryptUtil {

    private static final String privateKey;
    private static final String publicKey;

    static {
        try {
            // 生成加密密钥
            String[] keyPair = ConfigTools.genKeyPair(512);
            privateKey = keyPair[0];
            publicKey = keyPair[1];
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (NoSuchProviderException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 加密字符串
     *
     * @param plainText 需要加密的字符串
     * @return 加密后的字符串
     */
    public static String encrypt(String plainText) {
        try {
            return ConfigTools.encrypt(privateKey, plainText);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 解密字符串
     *
     * @param plainText 需要解密的字符串
     * @return 解密之后的字符串
     */
    public static String decrypt(String plainText) {
        try {
            return ConfigTools.decrypt(publicKey, plainText);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static void main(String[] args) {
        System.out.println("Public key: " + publicKey);
        System.out.println("Private key: " + privateKey);
        String admin = "Frank.china990924";
        String adminEncrypt = encrypt(admin);
        System.out.println(adminEncrypt);

    }
}
